package com.noble.glamour.ui.start;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.noble.glamour.R;
import com.noble.glamour.bean.start.LoginResult;
import com.noble.glamour.module.logic.application.ModuleMgr;
import com.noble.library.base.BaseAppCompatActivity;
import com.noble.glamour.module.logic.baseui.LoadingDialog;
import com.noble.glamour.module.logic.config.UrlParam;
import com.noble.glamour.module.logic.request.HttpResponse;
import com.noble.glamour.module.logic.request.RequestComplete;
import com.noble.glamour.module.util.ChineseFilter;
import com.noble.glamour.module.util.UIShow;
import com.noble.library.third.ThirdConstant;
import com.noble.glamour.third.auth.OauthBack;
import com.noble.glamour.ui.utils.NoDoubleClickListener;
import com.noble.library.log.PToast;

import java.lang.ref.WeakReference;

/**
 * 手机号登陆
 */
public class RegMobileAct extends BaseAppCompatActivity implements RequestComplete {
    private OauthBack oauthBack;
    private EditText edtPhone, edtCode;
    private TextView getCode;
    private String phone, code;

    private final TimeHandler handler = new TimeHandler(this);
    private SendEnableThread sendthread = null;

    private boolean isLogin = false;  // 是否可进行验证码校验操作

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.reg_mobile_act);
        initView();
        initCallback();
    }

    private void initCallback() {
        if (oauthBack == null) {
            oauthBack = new OauthBack(this);
            ModuleMgr.getAuthMgr().setCallback(oauthBack);
        }
    }

    private void initView() {
        edtPhone = (EditText) findViewById(R.id.login_mobile);
        edtCode = (EditText) findViewById(R.id.login_code);
        getCode = (TextView) findViewById(R.id.login_get_code);
        getCode.setOnClickListener(clickListener);
        findViewById(R.id.login_btn).setOnClickListener(clickListener);
        findViewById(R.id.login_wx).setOnClickListener(clickListener);
    }

    private NoDoubleClickListener clickListener = new NoDoubleClickListener() {
        @Override
        public void onNoDoubleClick(View v) {
            switch (v.getId()) {
                case R.id.login_wx:
                    ModuleMgr.getAuthMgr().onLogin(ThirdConstant.WECHAT);
                    break;

                case R.id.login_get_code: // 获取验证码
                    if (validPhone()) {
                        ModuleMgr.getLoginMgr().reqSendCode(phone, RegMobileAct.this);
                        if (sendthread == null || sendthread.getState() == Thread.State.TERMINATED) {
                            sendthread = new SendEnableThread();
                            getCode.setClickable(false);
                            sendthread.start();
                        }
                    }
                    break;

                case R.id.login_btn:    // 手机号验证码登陆
                    sendCode();
                    break;
                default:
                    break;
            }
        }
    };

    private void sendCode() {
        code = edtCode.getText().toString();
        if (isLogin && !TextUtils.isEmpty(code)) {
            LoadingDialog.show(this, getString(R.string.login_ing));
            ModuleMgr.getLoginMgr().reqVerifyCode(phone, code, RegMobileAct.this);
            return;
        }
        PToast.showShort(getString(R.string.code_error));
    }

    private boolean validPhone() {
        phone = edtPhone.getText().toString();
        if ("".equals(phone)) {
            PToast.showShort(getResources().getString(R.string.toast_phone_isnull));
            return false;
        }
        if (!ChineseFilter.isPhoneNumber(phone)) {
            PToast.showShort(getResources().getString(R.string.toast_phone_iserror));
            return false;
        }
        return true;
    }

    @Override
    protected boolean isImmersionBar() {
        return false;
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (ThirdConstant.mPlatform == ThirdConstant.WECHAT)
            LoadingDialog.closeLoadingDialog();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ModuleMgr.getAuthMgr().release();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // QQ登录回调
        ModuleMgr.getAuthMgr().onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onRequestComplete(HttpResponse response) {
        PToast.showShort(response.getMsg());

        // 发送验证码
        if (response.getUrlParam() == UrlParam.reqSendCode) {
            isLogin = response.isOk();
            return;
        }

        // 手机验证码验证
        if (response.getUrlParam() == UrlParam.reqVerifyCode) {
            LoadingDialog.closeLoadingDialog(500);
            if (!response.isOk()) return;

            LoginResult data = (LoginResult) response.getBaseData();
            ModuleMgr.getLoginMgr().setCookie(data.getAuth());
            ModuleMgr.getLoginMgr().putAllLoginInfo(data.getUid(), "", true);

            if (data.isNew()) {   // 新用户
                UIShow.showRegInfoAct(this, ThirdConstant.NORMAL_LOGIN, phone);
                return;
            }

            // 老用户： 去请求个人资料
            ModuleMgr.getCenterMgr().reqMyInfo(new RequestComplete() {
                @Override
                public void onRequestComplete(HttpResponse response) {
                    UIShow.showMainClearTask(RegMobileAct.this);
                }
            });
        }
    }

    private static class TimeHandler extends Handler {
        private final WeakReference<RegMobileAct> mActivity;

        TimeHandler(RegMobileAct act) {
            this.mActivity = new WeakReference<>(act);
        }

        @Override
        public void handleMessage(Message msg) {
            RegMobileAct act = mActivity.get();
            if (act != null) {
                if (msg.what > 0) {
                    act.getCode.setText(String.format(act.getString(R.string.bt_send_code_press), msg.what));
                } else {
                    act.getCode.setText(act.getResources().getString(R.string.bt_send_code_normal));
                    act.getCode.setClickable(true);
                }
            }
        }
    }

    private class SendEnableThread extends Thread {
        public void run() {
            int count = 60;
            while (count >= 0) {
                try {
                    Thread.sleep(1000);
                    handler.sendEmptyMessage(count);
                } catch (Exception e) {
                    break;
                }
                count--;
            }
        }
    }
}
